package com.avalon.erp.sys.addon.base.controller;

import com.avalon.core.context.SystemConstant;
import com.avalon.erp.sys.addon.base.service.UserService;
import com.avalon.core.exception.AvalonException;
import com.avalon.core.exception.FieldCheckException;
import com.avalon.core.model.RecordRow;
import com.avalon.core.util.BCryptUtil;
import com.avalon.core.util.ObjectUtils;
import com.avalon.core.redis.RedisCommon;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/")
@Slf4j
public class HomeController {

    @Autowired
    private RedisCommon redisCommon;
    @Autowired
    private UserService userService;

    @PostMapping("login")
    public RecordRow sysLogin(@RequestBody Map<String, Object> param) throws AvalonException {
        String name = param.get("username").toString();
        String password = param.get("password").toString();
        RecordRow login = userService.login(name, password);

        if (ObjectUtils.isNull(login) || ObjectUtils.isEmpty(login)) {
            throw new FieldCheckException("账号或密码错误");
        }

        String token = BCryptUtil.simpleUUID();
        login.put("token", token);
        String s = login.convert2Json();
        redisCommon.set(SystemConstant.TOKEN_PREFIX + token, s);
        return login;
    }


    @GetMapping("test")
    public String test() throws AvalonException {
        return "OK";
    }
}
